package com.woniuxy.filter;

import com.woniuxy.pojo.SysUser;
import com.woniuxy.service.PermissionService;
import com.woniuxy.service.RoleService;
import com.woniuxy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    //每次验证权限的时候执行
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("===============验证权限的时候被调用===================");
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        SysUser user=this.userService.getSysUserByLoginName((String)principalCollection.getPrimaryPrincipal());
        if(user!=null){
            List<String> roles=this.roleService.getRolesByUserId(user.getId());
            List<String> permissions=this.permissionService.getPermissionByUserId(user.getId());
            if(roles!=null&&roles.size()>0){
                authorizationInfo.addRoles(roles);
            }
            if(permissions!=null&&permissions.size()>0) {
                authorizationInfo.addStringPermissions(permissions);
            }
        }
        return null;
    }
    //登录执行
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("***********用户认证的时候被调用******************");
        String loginname=(String)authenticationToken.getPrincipal();
        SysUser user=userService.getSysUserByLoginName(loginname);
        if(user!=null){
            return new SimpleAuthenticationInfo(loginname,user.getPassword(),null,getName());
        }
        return null;
    }
}